package org.ztest.thrift;

import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
import org.ztest.thrift.echo.Echo;
import org.ztest.thrift.tutorial.Calculator;

// 非阻塞型服务器
public class JavaMultiplexServer
{
	public static void main(String[] args) throws Exception
	{
		// 复用器
		TMultiplexedProcessor multiplex = new TMultiplexedProcessor();
		
		CalculatorHandler handler1 = new CalculatorHandler();
		Calculator.Processor<CalculatorHandler> processor1 = new Calculator.Processor<CalculatorHandler>(handler1);
		multiplex.registerProcessor("CALCULATOR", processor1);
		
		EchoHandler handler2 = new EchoHandler();
		Echo.Processor<EchoHandler> processor2 = new Echo.Processor<EchoHandler>(handler2);
		multiplex.registerProcessor("ECHO", processor2);
		
		// 非阻塞型服务器
		TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(9090);
		// 协议需要适配客户端
		TProtocolFactory protocolFactory = new TCompactProtocol.Factory();
		// 1 非阻塞服务器单线程
//		TNonblockingServer.Args arg = new TNonblockingServer.Args(serverTransport);
//		arg.processor(multiplex);
//		arg.protocolFactory(protocolFactory);
//		TNonblockingServer server = new TNonblockingServer(arg);
		// 2 半同步半异步服务器，非阻塞多线程，io线程和业务线程均可配置
		TThreadedSelectorServer.Args arg = new TThreadedSelectorServer.Args(serverTransport);
		arg.processor(multiplex);
		arg.protocolFactory(protocolFactory);
		arg.selectorThreads(1);
		arg.workerThreads(1);
		TThreadedSelectorServer server = new TThreadedSelectorServer(arg);
//		// 3 半同步半异步服务器，非阻塞，接受连接与io处理均在同一个线程完成，业务在线程池完成
//		THsHaServer.Args arg = new THsHaServer.Args(serverTransport);
//		arg.processor(multiplex);
//		arg.protocolFactory(protocolFactory);
//		THsHaServer server = new THsHaServer(arg);
		
		server.serve();
	}
}
